﻿using DMSystem_Sqlite_WebAPI.Modals;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;

namespace DMSystem_Sqlite_WebAPI.Filters
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<GlobalExceptionFilter> _logger;

        public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
        {
            _logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            var ex = context.Exception;

            _logger.LogError(ex, "❌ 未捕获的异常: {Message}", ex.Message);

            context.Result = new ObjectResult(ApiResponse.Fail("服务器内部错误", ex.Message))
            {
                StatusCode = 200
            };

            context.ExceptionHandled = true;
        }
    }
}
